package com.foton.logistic.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.foton.logistic.base.BaseApplication;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.LocationUtil;
import com.foton.logistic.util.TimeUtil;
import com.foton.logistic.util.tool.LogUtil;


public class OutReceiver extends BroadcastReceiver{
    AlarmManager alarms;
    PendingIntent pendingIntent;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(BaseConstant.ACTION_ALARM)){
            LocationUtil locationUtil = LocationUtil.getInstance();

            try {
                setAlarm(context);
                long cTime = System.currentTimeMillis();
                LogUtil.e("ALARM_ACTION----------------" + TimeUtil.formatServiceTime2("" + System.currentTimeMillis()) + "    " + (cTime - BaseApplication.lastLocTime));
                if ((cTime- BaseApplication.lastLocTime)>BaseApplication.LOCTIME){
                    if (locationUtil!=null){
                        locationUtil.location(""+BaseApplication.LOCTIME);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public void setAlarm(Context context){
        alarms =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        int alarmType = AlarmManager.RTC_WAKEUP;
        long timeOrLengthofWait = BaseApplication.LOCTIME;
        String ALARM_ACTION =BaseConstant.ACTION_ALARM;
        long triggerAtTime = System.currentTimeMillis()+timeOrLengthofWait;
        Intent intentToFire = new Intent(ALARM_ACTION);
        pendingIntent = PendingIntent.getBroadcast(context, 0, intentToFire, 0);
        cancelAlarm();
        alarms.set(alarmType, triggerAtTime, pendingIntent);
    }

    public void cancelAlarm(){
        try {
            alarms.cancel(pendingIntent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}